#include "codeeditor.h"
#include <QtGui>
#include <vector>
#include <string>
using std::string;
CodeEditor::CodeEditor(QWidget *parent) : WidgetBase(parent)
{
	prePara = 0;
	nowPara = 0;
	prePos = 0;
	nowPos = 0;

	addKeyWord();

	connect(this,SIGNAL(textChange()),this,SLOT(changeKeyWord()));
	connect(this,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(updatePos(int,int)));
}

void CodeEditor::addKeyWord()
{
	string keyword[31] = { "char","short","int","unsigned",
						  "long","float","double","struct",
						  "union","void","enum","signed",
						  "const","volatile","typedef","auto",
						  "register","static","extern","break",
						  "case","continue","default","do",
						  "else","for","goto","if",
						  "return","switch","while"
						};
    for(int i = 0;i < 31;i++)
	{
		QString tmp = QString(QString::fromLocal8Bit(keyword[i].c_str()));  
		keyWord.insert(tmp);
	}
}

void CodeEditor::updatePos(int para,int pos)
{
	prePara = nowPara;
	prePos = nowPos;
	nowPara = para;
	nowPos = pos;
}

void CodeEditor::changeTheColor(int para,int start,int length,bool change = true)
{
	
}

void CodeEditor::dealWithPara(int para)
{
	int start;
	QString content = this->document()->findBlockByLineNumber(para).text();
	for(int i = 0;i < content.length();i++)
	{
		if(content[i].isLetter())
		{
			QString tmp = "";
			start = i;
			while(i < content.length() && content[i].isLetter())
				tmp += content[i];
			if(keyWord.find(tmp) != keyWord.end())
			{
				changeTheColor(para,start,tmp.length());
			}
			else
			{
				changeTheColor(para,start,tmp.length(),false);
			}
		}
	}
}

void CodeEditor::changeKeyWord()
{
	 disconnect(this,SIGNAL(textChange()),this,SLOT(changeKeyWord()));
	disconnect(this,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(updatePos(int,int)));
	for(int i = prePara;i <= nowPara;i++)
	{
		dealWithPara(i);
	}
	connect(this,SIGNAL(textChange()),this,SLOT(changeKeyWord()));
	connect(this,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(updatePos(int,int)));
}

CodeEditor::~CodeEditor()
{

}
